<script setup lang='ts'>


// TODO ff大王想要一个彩蛋

import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { getBirdInfoByIdService } from '@/api/birds'
import { useBirdStore } from '@/stores/bird'
import { addCollectionService } from '@/api/collection';
import { useUserStore } from '@/stores/user'
import { deleteCollectionService, getCollectionListByUIDAndBirdIdService } from '@/api/collection';
import { ArrowLeft } from '@element-plus/icons-vue'

const userStore = useUserStore()

const birdStore = useBirdStore()

const activeIndex = ref('')
const handleSelect = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}

const router = useRouter()
const route = useRoute()

//根据路径更新activeIndex
const updateActiveIndex = (path) => {
    
    // pc端高亮规则
    if (path.includes('/birdPicture')) {
        activeIndex.value = '5'
    } else if (path.includes('/birdSong')) {
        activeIndex.value = '6'
    } else if (path.includes('/formAndCts')) {
        activeIndex.value = '3'
    } else if (path.includes('/growthDistribution')) {
        activeIndex.value = '2'
    } else if (path.includes('/lifeHabits')) {
        activeIndex.value = '4'
    } else if (path.includes('/home/birdDetail/')) {
        activeIndex.value = '1'
    } else {
        activeIndex.value = ''
    }
}

//初始化
// updateActiveIndex(route.path)
// console.log("route.path:" +  route.path)
// console.log("activeIndex.value:" +  activeIndex.value)

// 监听路由变化并更新 activeIndex
// 来根据当前显示的页面改变导航栏高亮
watch(route, (newRoute) => {
    updateActiveIndex(newRoute.path)
},
    { immediate: true }
)


const toBaseIntroduction = (birdId: number) => {
    router.push('/home/birdDetail/' + birdId)

}

const toBirdPicture = (birdId: number) => {
    router.push('/home/birdDetail/' + birdId + '/birdPicture')
}

const toBirdSong = (birdId: number) => {
    router.push('/home/birdDetail/' + birdId + '/birdSong');
    // closeMoreMenu();
}

const toFormAndCts = (birdId: number) => {
    router.push('/home/birdDetail/' + birdId + '/formAndCts')
}

const toGrowthDistribution = (birdId: number) => {
    router.push('/home/birdDetail/' + birdId + '/growthDistribution')
}

const toLifeHabits = (birdId: number) => {
    router.push('/home/birdDetail/' + birdId + '/lifeHabits')
}

// 获取传过来的鸟类id
// 获取路由中包含的鸟类id参数
const birdId = route.params.id
// console.log(birdId)



//定义一个对象用于存储获取的鸟类信息
const birdInfo = ref({
    id: 0,
    createdAt: '',
    updatedAt: '',
    morphologyAndFeatures: '',
    name: '',
    habits: '',
    species: '',
    imageUrl: '',
    soundUrl: '',
    description: '',
    growthAndDistribution: ''
})

//定义一个对象用于存储获取的鸟类的种类信息
const speciesInfo = ref({
    class: '',
    order: '',
    family: '',
    genus: '',
    species: ''
})

// 是否已收藏
const isCollected = ref(false);

//调用后台接口根据birdId和UID获取鸟类收藏信息
const getCollectionListByUIDAndBirdId = async () => {

    let result = await getCollectionListByUIDAndBirdIdService(userStore.user.uid, birdId)

    //输出结果看一下
    // console.log(result)
    // console.log(result.data != null)

    //如果成功并且能够查询到信息则返回ture，查询不到信息则返回false，如果失败则提示
    if (result.code === 200) {
        if (result.data != null) {
            isCollected.value = true;
        } else {
            isCollected.value = false;
        }
    } else {
        ElMessage.error(result.msg ? result.msg : '获取鸟类收藏信息失败');
    }

}
getCollectionListByUIDAndBirdId()

// 点击收藏/取消收藏按钮
const toggleCollection = async () => {
    // 这里你需要获取用户的 UID，假设你已经通过某种方式获取到了 UID
    const uid = userStore.user.uid;

    if (isCollected.value) {
        // 取消收藏

        deleteCollection(uid, birdId)

    } else {
        // 收藏
        addCollection(uid, birdId);

    }


};

//调用后端接口添加收藏
const addCollection = async (uid, birdId) => {

    let result = await addCollectionService(uid, birdId)

    if (result.code === 200) {
        ElMessage.success('收藏成功');
        isCollected.value = true; // 更新状态
    } else {
        ElMessage.error(result.msg ? result.msg : '收藏失败');
    }

}

//调用后端接口删除收藏
const deleteCollection = async (uid, birdId) => {

    let result = await deleteCollectionService(uid, birdId)

    if (result.code === 200) {
        ElMessage.success('取消收藏成功');
        isCollected.value = false; // 更新状态
    } else {
        ElMessage.error(result.msg ? result.msg : '取消收藏失败');
    }

}

//调用后端接口根据id获取鸟类信息
const getBirdInfoById = async () => {

    let result = await getBirdInfoByIdService(birdId)

    //如果成功，则将数据赋值给birdInfo，失败则提示
    if (result.code == 200) {

        birdInfo.value = result.data

        //将species转化并存起来
        speciesInfo.value = JSON.parse(birdInfo.value.species);
        // console.log(speciesInfo.value)

        //放到pinia里存起来方便取用
        // birdStore.setBird(birdInfo.value)
        birdStore.setId(birdInfo.value.id)
        birdStore.setName(birdInfo.value.name)
        birdStore.setSpecies(birdInfo.value.species)
        birdStore.setHabits(birdInfo.value.habits)
        birdStore.setMorphologyAndFeatures(birdInfo.value.morphologyAndFeatures)
        birdStore.setDescription(birdInfo.value.description)
        birdStore.setGrowthAndDistribution(birdInfo.value.growthAndDistribution)
        birdStore.setImageUrl(birdInfo.value.imageUrl)
        birdStore.setSoundUrl(birdInfo.value.soundUrl)
        birdStore.setCreatedAt(birdInfo.value.createdAt)
        birdStore.setUpdatedAt(birdInfo.value.updatedAt)

        //输出来看一下
        // console.log(birdStore.bird)

    } else {
        ElMessage.error(result.msg ? result.msg : '获取鸟类信息失败')
    }

}
getBirdInfoById();

const goBack = () => {
    router.back();
}

// 移动端适配
const isMobile = ref(false);

const checkIsMobile = () => {
    isMobile.value = window.innerWidth <= 600;
};

onMounted(() => {
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', checkIsMobile);
});

// 手动关闭sub-memu
const moreDropdownRef = ref();

function handleMoreMenuClick(command) {
    // activeIndex.value = command;
    switch (command) {
        case '3':
            toFormAndCts(birdInfo.value.id);
            break;
        case '4':
            toLifeHabits(birdInfo.value.id);
            break;
        case '5':
            toBirdPicture(birdInfo.value.id);
            break;
        case '6':
            toBirdSong(birdInfo.value.id);
            break;
    }

    // 手动关闭 dropdown
    moreDropdownRef.value?.hide();
}



</script>

<template>
    <div class="container">
        <el-card class="bird-card" style="width: 90%">
            <template #header>
                <div class="birdBaseInfo-header">
                    <div style="display: flex; align-items: center;">
                        <el-button type="text" @click="goBack" style="margin-right: 10px;">
                            <el-icon>
                                <ArrowLeft />
                            </el-icon>
                            返回
                        </el-button>
                        <div>{{ birdInfo.name }}</div>
                    </div>
                    <div class="birdBaseInfo-star">

                        <el-icon :name="isCollected ? 'star-on' : 'star-off'" @click="toggleCollection" :style="{
                            color: isCollected ? 'orange' : 'black',
                            cursor: 'pointer'
                        }" size="30">
                            <Star />
                        </el-icon>
                    </div>
                </div>
            </template>
            <el-row class="birdBaseInfo">

                <el-col class="birdBaseInfo-left" :span="12">
                    <img :src="birdInfo.imageUrl" style="width: 100%" />
                </el-col>
                <el-col class="birdBaseInfo-right" :span="12">
                    <el-row class="birdBaseInfo-right_content">
                        英文名：XXXXXX
                    </el-row>
                    <el-row class="birdBaseInfo-right_content">
                        纲：{{ speciesInfo.class }}
                    </el-row>
                    <el-row class="birdBaseInfo-right_content">
                        目：{{ speciesInfo.order }}
                    </el-row>
                    <el-row class="birdBaseInfo-right_content">
                        科：{{ speciesInfo.family }}
                    </el-row>
                    <el-row class="birdBaseInfo-right_content">
                        属：{{ speciesInfo.genus }}
                    </el-row>
                </el-col>

            </el-row>
            <el-row class="birdDetailInfo">
                <el-row class="birdDetailInfo-navigator">
                    <el-menu :ellipsis=false :default-active="activeIndex" class="el-menu-demo" mode="horizontal"
                        @select="handleSelect">
                        <el-menu-item index="1" @click="toBaseIntroduction(birdInfo.id)">基本介绍</el-menu-item>
                        <el-menu-item index="2" @click="toGrowthDistribution(birdInfo.id)">生长分布</el-menu-item>


                        <!-- 移动端收纳菜单项 -->
                        <template v-if="isMobile">
                            <el-menu-item index="more">
                                <el-dropdown class="more-dropdown" ref="moreDropdownRef" trigger="click" @command="handleMoreMenuClick">
                                <el-button type="text" class="mobile-more-menu-button">
                                    更多<el-icon><arrow-down /></el-icon>
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item command="3" :class="{ 'dropdown-item-active': activeIndex === '3' }">形态及特征</el-dropdown-item>
                                        <el-dropdown-item command="4" :class="{ 'dropdown-item-active': activeIndex === '4' }">生活习性</el-dropdown-item>
                                        <el-dropdown-item command="5" :class="{ 'dropdown-item-active': activeIndex === '5' }">鸟类图片</el-dropdown-item>
                                        <el-dropdown-item command="6" :class="{ 'dropdown-item-active': activeIndex === '6' }">鸟叫声</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                            </el-menu-item>
                        </template>

                        <!-- PC 端显示所有 -->
                        <template v-else>
                            <el-menu-item index="3" @click="toFormAndCts(birdInfo.id)">形态及特征</el-menu-item>
                            <el-menu-item index="4" @click="toLifeHabits(birdInfo.id)">生活习性</el-menu-item>
                            <el-menu-item index="5" @click="toBirdPicture(birdInfo.id)">鸟类图片</el-menu-item>
                            <el-menu-item index="6" @click="toBirdSong(birdInfo.id)">鸟叫声</el-menu-item>
                        </template>
                    </el-menu>
                </el-row>
                <el-row class="birdDetailInfo-content">
                    <router-view :birdId="birdInfo.id"></router-view>

                    <!-- <Suspense>
                        <template #default>
                            <router-view :birdId="birdInfo.id"></router-view>
                        </template>
                        <template #fallback>
                            <div>Loading...</div>
                        </template>
                    </Suspense> -->

                </el-row>

            </el-row>


        </el-card>
    </div>
</template>

<style scoped>
.container {
    display: flex;
    justify-content: center;
    /* align-items: center; */
    /* margin: 10px; */
    /* padding: 10px; */
    /* padding-top: 10%; */
    height: auto;
    width: 100%;
}

.bird-card {
    width: 100%;
    height: 100%;
    padding: 10px;
    margin: 10px;
}

.birdBaseInfo-right_content {
    height: 20%;
    align-items: center;
    justify-content: center;
}

.birdDetailInfo {
    flex-direction: column;

}

.birdDetailInfo-content {
    flex-direction: column;
    height: auto;
    width: auto;
    padding: 10px;
    /* 居中 */
    display: flex;
    justify-content: center;
    align-items: center;
}

.birdBaseInfo-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.birdDetailInfo-navigator {
    display: flex;
    /* justify-content: left; */
    /* align-items: center; */
    width: 100%;
}

.el-menu-demo {
    width: 100%;
}

/* .more-dropdown{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 96px;
    cursor: pointer;
} */

::v-deep(.el-dropdown-menu__item.dropdown-item-active) {
  background-color: var(--el-color-primary-light-9); /* 或你自定义的颜色 */
  color: var(--el-color-primary);
  font-weight: bold;
}
</style>